#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <math.h>
#include <linux/input.h>
#include <stdlib.h>

int main()
{
    int fd_touch = open("/dev/input/event0", O_RDWR);
    if (fd_touch < 0)
    {
        printf("open touch error %s\n", strerror(errno));
        return -1;
    }
    printf("open touch success\n");

    // 读取触摸屏数据
    struct input_event buf;
    int sx = -1, sy = -1, ex = -1, ey = -1;
    int isPressDown = 0;
    while (1)
    {
        memset(&buf, 0, sizeof(buf));
        read(fd_touch, &buf, sizeof(buf));
        // printf("type = %d, code = %d, value = %d\n", buf.type, buf.code, buf.value);

        if (buf.type == EV_ABS)
        {
            if (isPressDown == 0)
            {
                if (buf.code == ABS_X)
                {
                    sx = buf.value;
                }
                if (buf.code == ABS_Y)
                {
                    sy = buf.value;
                }
            }
            else
            {
                if (buf.code == ABS_X)
                {
                    ex = buf.value;
                }
                if (buf.code == ABS_Y)
                {
                    ey = buf.value;
                }
            }
        }
        // 在按下或松开时打印坐标
        if (buf.type == EV_KEY && buf.code == BTN_TOUCH)
        {
            if (buf.value == 1)
            { // 按下
                // printf("press down sx = %d, sy = %d, ex = %d, ey = %d\n", sx, sy, ex, ey);
                isPressDown = 1;
            }
            else
            { // 松开
                // printf("press up sx = %d, sy = %d, ex = %d, ey = %d\n", sx, sy, ex, ey);
                isPressDown = 0;
                if (abs(sx - ex) > abs(sy - ey))
                {
                    if (ex != -1 && ey != -1 && abs(sx - ex) > 100)
                    {
                        if (sx > ex)
                        {
                            printf("👈\n");
                        }
                        else
                        {
                            printf("👉\n");
                        }
                    }
                }
                else
                {
                    if (ey != -1 && ey != -1 && abs(sy - ey) > 100)
                    {
                        if (sy > ey)
                        {
                            printf("👆\n");
                        }
                        else
                        {
                            printf("👇\n");
                        }
                    }
                }
                sx = -1, sy = -1, ex = -1, ey = -1;
            }
        }
    }

    close(fd_touch);
    return 0;
}


